package com.hrm.system.service;


import com.baidu.aip.util.Base64Util;
import com.hrm.common.util.IdWorker;
import com.hrm.domain.system.QRCode;
import com.hrm.domain.system.User;
import com.hrm.domain.system.response.FaceLoginResult;
import com.hrm.system.dao.UserDao;
import com.hrm.system.utils.BaiduAiUtil;
import com.hrm.system.utils.QRCodeUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

@Service
public class FaceLoginService {

    @Value("${qr.url}")
    private String url;
    @Autowired
    private IdWorker idWorker;
    @Autowired
    private QRCodeUtil qrCodeUtil;
    @Resource //根据名称匹配
    private RedisTemplate<String, Object> redisTemplate;
    @Autowired
    private BaiduAiUtil baiduAiUtil;
    @Autowired
    private UserDao userDao;

    //创建二维码
    public QRCode getQRCode() throws Exception {
        //创建唯一标识码
        String code = idWorker.nextId() + "";
        //生成二维码(内容是url+id)
        String dataUrl = qrCodeUtil.crateQRCode(url + "?code=" + code);
        //存入当前二维码状态入redis
        FaceLoginResult faceLoginResult = new FaceLoginResult("-1"); //-1未使用
        redisTemplate.boundValueOps(getCacheKey(code)).set(faceLoginResult, 10, TimeUnit.MINUTES);
        return new QRCode(code, dataUrl);
    }

    //根据唯一标识，查询用户是否登录成功
    public FaceLoginResult checkQRCode(String code) {
        //redis中获取
        return (FaceLoginResult) redisTemplate.opsForValue().get(getCacheKey(code));
    }

    //扫描二维码之后，使用拍摄照片进行登录
    //返回userid
    public String loginByFace(String code, MultipartFile attachment) throws Exception {
        String res = baiduAiUtil.faceSearch(Base64Util.encode(attachment.getBytes()));
        //登录后更改二维码状态
        FaceLoginResult faceLoginResult = new FaceLoginResult("0");
        if (res != null) {
            User user = userDao.findById(res).get();
            if (user != null) {
                //创建登录token
                Subject subject = SecurityUtils.getSubject();
                subject.login(new UsernamePasswordToken(user.getMobile(), user.getPassword()));
                String token = subject.getSession().getId() + ""; //获取sessionid
                faceLoginResult = new FaceLoginResult("1", token, res);
            }
        }
        redisTemplate.boundValueOps(getCacheKey(code)).set(faceLoginResult, 30, TimeUnit.MINUTES);
        return res;
    }

    //构造缓存key
    private String getCacheKey(String code) {
        return "qrcode_" + code;
    }
}
